package com.peza.postman.monitor;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class DelegatingTimedMonitor  extends QuartzJobBean{
	
	private static final String APPLICATION_CONTEXT_KEY = "applicationContext";  
	private static final String JOB_BEAN_NAME_KEY = "job.bean.name";  
		
	@Override  
	protected final void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {  
	    SchedulerContext schedulerContext = null;  
	    
	    try {  
	        schedulerContext = jobExecutionContext.getScheduler().getContext();  
	    } catch(SchedulerException e) {  
	        throw new JobExecutionException("Failure accessing scheduler context", e);  
	    }
	    
	    ApplicationContext appContext = (ApplicationContext) schedulerContext.get(APPLICATION_CONTEXT_KEY);  
	    String jobBeanName = (String) jobExecutionContext.getJobDetail().getJobDataMap().get(JOB_BEAN_NAME_KEY);  
	    TimedMonitor monitor = (TimedMonitor) appContext.getBean(jobBeanName);  
	    
	    try {  
	        monitor.init(jobExecutionContext);  
	        monitor.execute();  
	    } finally {  
	        monitor.destroy();  
	    }  
	}  
}
